package com.fc.remoting.codec;

import java.nio.ByteBuffer;

import com.fc.remoting.message.RemotingMessage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RemotingMessageEncoder extends MessageToByteEncoder<RemotingMessage>  {
	private static final byte FIRST_FLAG = 0X66;
	private static final byte SECOND_FLAG = 0X63;
	private static final byte[] FLAGS = {FIRST_FLAG,SECOND_FLAG};
	@Override
	protected void encode(ChannelHandlerContext ctx, RemotingMessage msg, ByteBuf out) throws Exception {
		if (msg == null)
			return;
		try {
			out.writeBytes(FLAGS);
            ByteBuffer byteBuffer = msg.build();
            out.writeBytes(byteBuffer);
            byte[] body = msg.getBody();
            if(body != null){
            	out.writeBytes(body);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}